package com.enterprise.viewer.client;

import com.enterprise.viewer.client.presenter.Presenter;
import com.enterprise.viewer.client.presenter.RootPresenter;
import com.enterprise.viewer.client.view.RootView;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;

/**
 * Manages the event bus and services
 * @author buddha
 *
 */
public class AppController implements Presenter, ValueChangeHandler<String>{
	private HasWidgets container;
	private final SimpleEventBus eventBus;
	private final EnterpriseViewerServiceManager servicemanager;  

	public AppController() {  		
		bind();
		
		eventBus = new SimpleEventBus();
		servicemanager = new EnterpriseViewerServiceManager(eventBus);
	}	

	private void bind()
	{
		History.addValueChangeHandler(this);		
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		String token = event.getValue();

		if (token != null) {
			Presenter presenter = null;

			if(token.equals("root")) {
				presenter = new RootPresenter(eventBus, new RootView());
			}

			if (presenter != null) {
				presenter.go(container);
			}
		}
	}

	@Override
	public void go(HasWidgets container) {
		this.container = container;

		if ("".equals(History.getToken())) {
			History.newItem("root");
		}
		else {
			History.fireCurrentHistoryState();
		}
	}
}
